'''
Created on 2014-4-21

@author: shen
'''

import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
from numpy.lib.function_base import average

from read_list_from_file.read_price_list import Get_Price_List


def draw(ASIN_list , price_list):
    # Example data
    y_pos = np.arange(len(ASIN_list))
    performance = price_list
    error = 0
    
    plt.barh(y_pos, performance, xerr=error, align='center', alpha=0.4)
    plt.yticks(y_pos, ASIN_list)
    plt.xlabel('average price')
    plt.title('the average price of each day')
    
    plt.show()

    # the example of draw a chart of price scatter
    #show the average price of products in a same time(by hour)
if __name__ == '__main__':
    getList = Get_Price_List();
    
    list = getList.get_infolist()
    list1=[]
    pre=''
    #separate the date and time for better comparison
    for item in list:
        date = item['time'].split(' ')[0]
        time = item['time'].split(' ')[1]
        print item['time']
        list1.append({'date':date,'time':time,'price':item['price']})
    
    #sort the list
    list1.sort(key=lambda x:(x['date'],x['time']), reverse=False)
    
    #separate the time to format(hour,minute,second)
    for item in list1:
        temp_str = item['time']
        temp_split = temp_str.split(':')
        item['time'] = [int(temp_split[0]) , int(temp_split[1]) , int(temp_split[2])]
    
    i=0
    temp_list=[]
    
    date_list=[]
    avg_price_list=[]
    
    pre = list1[0]['date']
    pre_hour = list1[0]['time'][0]
    
    #generate the list of time(day_hour) and avg_price
    while True:
        if i==len(list1):
            break
        if list1[i]['date']==pre and list1[i]['time'][0]==pre_hour:
            temp_list.append(list1[i]['price'])
        else:
            pre = list1[i]['date']
            pre_hour = list1[i]['time'][0]
            date_list.append(pre +' '+ str(pre_hour))
            avg_price_list.append(average(temp_list))
            temp_list=[]
        i=i+1
        
    draw(date_list, avg_price_list)
        